package com.jackstraw.jack_base.datasource.database.generator.controller;

import com.jackstraw.jack_base.datasource.common.contextholder.DataSourceContextHolder;
import com.jackstraw.jack_base.datasource.common.entity.enums.DataSourceTypeEnum;
import com.jackstraw.jack_base.datasource.database.generator.entity.GeneratorVo;
import com.jackstraw.jack_base.datasource.database.generator.service.GeneratorService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Controller
@RequestMapping("/generator")
public class GeneratorController {

    @Autowired
    private GeneratorService generatorService;

    /**
     * 生成代码
     */
    @RequestMapping("/generator")
    public void code(@RequestBody GeneratorVo generatorVo, HttpServletResponse response) throws IOException {
        try {
            DataSourceContextHolder.setDataSourceName(DataSourceTypeEnum.database, generatorVo.getDataSourceName());

            byte[] data = generatorService.generatorCode(generatorVo);

            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"generator.zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");

            IOUtils.write(data, response.getOutputStream());
        } finally {
            DataSourceContextHolder.clearDataSourceName(DataSourceTypeEnum.database);
        }

    }
}
